// @Author miaoqing
// @Date 2024/02/22 14:38:00
// @Desc
package network

type MsgBuffer struct {
	readBuff  []byte
	writeBuff []byte
	maxMsgLen uint32
}

func newMsgBuffer() *MsgBuffer {
	return &MsgBuffer{
		readBuff:  make([]byte, 0),
		writeBuff: make([]byte, 0),
		maxMsgLen: 2 * 1024 * 1024,
	}
}

func (msgB *MsgBuffer) Read(conn *NetConn) ([][]byte, error) {
	buf := make([]byte, 1024)
	num, err := conn.Conn.Read(buf)
	if err != nil {
		return nil, err
	}
	if num > 0 {
		msgB.readBuff = append(msgB.readBuff, buf[:num]...)
	}
	return Decode(conn)
}

func (msgB *MsgBuffer) Write(conn *NetConn, data ...byte) error {
	msgB.writeBuff = append(msgB.writeBuff, data...)
	num, err := conn.Write(msgB.writeBuff)
	if err != nil {
		return err
	}
	if num > 0 {
		msgB.writeBuff = msgB.writeBuff[num:]
	}
	return nil
}
